package com.sneaker.shower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sneaker.shower.common.ThreadLocalCache;
import com.sneaker.shower.entity.domain.order.discount.OrderDiscountDO;
import com.sneaker.shower.entity.domain.order.SubOrderDO;
import com.sneaker.shower.entity.enums.OrderDiscountTypeEnum;
import com.sneaker.shower.mapper.OrderDiscountMapper;
import com.sneaker.shower.service.OrderDiscountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author Hechangjian
 * @version 1.0
 * @className OrderDiscountServiceImpl
 * @date 2019/12/02 10:50
 * @description
 * @program bath
 */
@Service
@Slf4j
public class OrderDiscountServiceImpl extends ServiceImpl<OrderDiscountMapper, OrderDiscountDO> implements OrderDiscountService {

    @Override
    public Boolean saveOrUpdateCouponDiscount(SubOrderDO subOrderDO, Long couponGuid, Integer discountType) {
        Assert.notNull(subOrderDO.getGuid(), "订单编号不能为空");
        Assert.notNull(discountType, "优惠类型不能为空");
        if (Objects.equals(OrderDiscountTypeEnum.COUPON.getType(), discountType)) {
            Assert.notNull(couponGuid, "优惠券编号不能为空");
        }
        OrderDiscountDO orderDiscountDO = getDiscount(subOrderDO.getGuid(), discountType);
        if (orderDiscountDO == null) {
            orderDiscountDO = new OrderDiscountDO();
            orderDiscountDO.setGuid(IdWorker.getId());
            orderDiscountDO.setUserGuid(Long.parseLong(ThreadLocalCache.get().getGuid()));
            orderDiscountDO.setDiscountType(discountType);
            orderDiscountDO.setOrderGuid(subOrderDO.getGuid());
            orderDiscountDO.setDiscountFee(subOrderDO.getOrderPrice());
        }
        orderDiscountDO.setCouponGuid(couponGuid);
        return this.saveOrUpdate(orderDiscountDO);
    }

    @Override
    public Boolean updateDiscountFee(Long discountGuid, BigDecimal discountFee) {
        OrderDiscountDO discountDO = this.getById(discountGuid);
        if (discountDO == null) {
            return false;
        }
        discountDO.setDiscountFee(discountFee);
        return this.updateById(discountDO);
    }

    @Override
    public OrderDiscountDO getDiscount(Long subOrderGuid, Integer discountType) {
        long userGuid = Long.parseLong(ThreadLocalCache.get().getGuid());
        return this.getOne(new LambdaQueryWrapper<OrderDiscountDO>()
                .eq(OrderDiscountDO::getUserGuid, userGuid)
                .eq(OrderDiscountDO::getOrderGuid, subOrderGuid)
                .eq(OrderDiscountDO::getDiscountType, discountType));
    }
}
